package com.mibox.common.utils.ticker;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public enum AppTicker {
    INSTANCE;

    private Timer mTimer;
    private long mSeconds = 0;
    private List<TickCallback> mTickers = new ArrayList<>();

    public void register(TickCallback callback) {
        mTickers.add(callback);
    }

    public void unregister(TickCallback callback) {
        mTickers.remove(callback);
    }

    public void start() {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mSeconds += 1;
                for (TickCallback tick : mTickers) {
                    try {
                        if (tick != null) {
                            tick.onSecondTick(mSeconds);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 0, 1000);
    }

    public void stop() {
        mTickers.clear();
        mTimer.cancel();
    }
}
